#!/usr/bin/env python3
import os
import sys
from scapy.all import FieldLenField, FieldListField, IntField, IPOption, ShortField, get_if_list, sniff
from scapy.layers.inet import _IPOption_HDR


def get_eth_interface():
    """获取第一个包含eth0的网络接口"""
    interfaces = [iface for iface in get_if_list() if "eth0" in iface]
    if not interfaces:
        print("未找到eth0接口")
        sys.exit(1)
    return interfaces[0]


class IPOption_MRI(IPOption):
    """用于交换机路径跟踪的MRI IP选项"""
    name = "MRI"
    option = 31
    fields_desc = [
        _IPOption_HDR,
        FieldLenField("length", None, fmt="B",
                     length_of="swids",
                     adjust=lambda pkt, l: l + 4),
        ShortField("count", 0),
        FieldListField("swids", [], IntField("", 0),
                      length_from=lambda pkt: pkt.count * 4)
    ]


def process_received_packet(packet):
    """处理接收到的数据包"""
    print("收到数据包:")
    packet.show2()
    sys.stdout.flush()


def main():
    """主函数：监听TCP数据包"""
    iface = get_eth_interface()
    print(f"在接口 {iface} 上监听")
    sys.stdout.flush()
    
    sniff(filter="tcp", iface=iface, prn=process_received_packet)


if __name__ == '__main__':
    main()